package com.my.study.deallock;

import com.my.study.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Carlos
 * @version 1.0
 * @Description 测试哲学家就餐死锁问题
 *
 * 定位死锁方法：
 * 1、使用jps定位进程id，再用jstack定位死锁信息
 * 2、使用jconsole工具
 *
 * @date 2021/5/18 8:06
 **/
public class TestDealLock {

    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");

        new Philosopher("苏格拉底", c1, c2).start();
        new Philosopher("柏拉图", c2, c3).start();
        new Philosopher("亚里士多德", c3, c4).start();
        new Philosopher("阿基米德", c4, c5).start();
        // 将(c5,c1) -> (c1, c5)，成了饥饿情况
        new Philosopher("罗翔", c5, c1).start();
    }

}

@Slf4j(topic = "c.Philosopher")
class Philosopher extends Thread{

    private Chopstick left;
    private Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (left) {
                synchronized (right) {
                    eat();
                }
            }
        }
    }

    private void eat() {
        log.debug("eating...");
        ThreadUtil.sleep(1);
    }

}

class Chopstick{
    private String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" +
                "name='" + name + '\'' +
                '}';
    }
}
